import {onActivated, onDeactivated, onMounted, onUnmounted, ref, toRaw, watch} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "@/stores";

export function userDataWatch(watchRealm: boolean, cb: any=undefined) {
    const store = useStore();
    const isActivated = ref(false);
    const needRefresh = ref(true);
    const hasInit = ref(false);
    const router = useRouter();
    const refList = ref();

    const refreshData = () => {
        if (needRefresh.value) {
            needRefresh.value = false;
            refList.value?.refreshData();
        }
    }

    const getWatch = () => {
        return watchRealm ? store.realms : store.platform;
    }

    const updatePlatformUi = async (r: boolean) => {
        if (r) {
            needRefresh.value = true;
            if (isActivated.value) {
                refreshData();
            }
        }
    }

    const doWatch = () => {
        watch(
            () => getWatch(),
            async (newVal: any, oldVal: any) => {
                const newRaw = toRaw(newVal);
                const oldRaw = toRaw(oldVal);

                if (oldRaw && newRaw.id !== oldRaw.id) {
                    await updatePlatformUi(true);
                }
            }, {immediate: true}
        );
        if (!watchRealm) {
            watch(
                () => store.tenant,
                async (newVal: any, oldVal: any) => {
                    const newRaw = toRaw(newVal);
                    const oldRaw = toRaw(oldVal);

                    if (oldRaw && newRaw.id !== oldRaw.id) {
                        await updatePlatformUi(true);
                    }
                }, {immediate: true}
            );
        }
    }

    const initList = () => {
        if (!hasInit.value) {
            hasInit.value = true;
            doWatch();
        }
    }

    onMounted(() => {
        console.log('router.currentRoute.value.meta.keepAlive', router.currentRoute.value.meta.keepAlive)
        if (!router.currentRoute.value.meta.keepAlive) {
            initList();
            refreshData();
        }
    })

    onActivated(() => {
        isActivated.value = true;
        initList();
        refreshData();
    })

    onDeactivated(() => {
        isActivated.value = false;
    })

    onUnmounted(() => {
    })

    return {
        refList,
    }
}
